<template>
    <!-- 支持多端自动适配的 SVG 图标 -->
    <svg
        class="han-icon"
        :style="{
            width: size + 'rpx',
            height: size + 'rpx',
            color: color
        }"
        aria-hidden="true"
    >
        <use :xlink:href="`#${iconPrefix}-${name}`" />
    </svg>
</template>

<script setup>
import { onMounted } from 'vue';

const props = defineProps({
    name: { type: String, required: true }, // 图标名称 (需与 Iconfont 项目一致)
    size: { type: [Number, String], default: 32 }, // 单位 rpx
    color: { type: String, default: '#666' }, // 支持所有 CSS 颜色格式
    iconPrefix: { type: String, default: 'icon' } // 与 Iconfont 项目配置一致
});

// 动态加载 Symbol（带错误重试机制）
const loadIcons = (retryCount = 0) => {
    const scriptId = 'iconfont-symbol';
    const maxRetry = 3;
    const iconfontUrl = `//at.alicdn.com/t/c/font_4891772_cu4ei8wtrpa.js`;

    if (!document.getElementById(scriptId)) {
        const script = document.createElement('script');
        script.src = `https:${iconfontUrl}?t=${Date.now()}`;
        script.id = scriptId;
        script.onload = () => console.log('Iconfont 加载成功');
        script.onerror = () => {
            if (retryCount < maxRetry) {
                console.warn(`图标加载失败，第 ${retryCount + 1} 次重试...`);
                setTimeout(() => loadIcons(retryCount + 1), 2000);
            } else {
                console.error('图标资源加载失败，请检查网络或配置');
            }
        };
        document.body.appendChild(script);
    }
};

// 在控制台查看已加载的图标
// console.log('已注册图标:', document.querySelectorAll('symbol[id^="icon-"]'));

onMounted(loadIcons);
</script>

<style scoped>
.han-icon {
    vertical-align: -0.15em;
    overflow: hidden;
    transition: all 0.3s;
    shape-rendering: geometricPrecision; /* 抗锯齿 */
    backface-visibility: hidden; /* 启用 GPU 加速 */
}
</style>
